#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import json
import random
import time
import os
from os.path import join as pjoin
import sys
"""
发送验证码邮件，并且将数据写入json以供前端查询
"""
UserID = sys.argv[1]
UserEmail = sys.argv[2]
UserIP = sys.argv[3]

def ranstr(num):
    # 猜猜变量名为啥叫 H
    H = 'abcdefghijklmnopqrstuvwxyz0123456789'
    salt = ''
    for i in range(num):
        salt += random.choice(H)
    return salt
verification_code = ranstr(4)
# 生成四位随机字符串作为验证码
date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# 格式化成2016-03-20 11:45:39形式

def SendEmail():
    print('Sending Email to :'+UserEmail)
    # 第三方 SMTP 服务
    mail_host = "smtp.exmail.qq.com"   # 设置SMTP服务器
    mail_user = "XXXXXXXXXXXXXX" # QQ邮箱，其他邮箱的也行
    mail_pass = "XXXXXXXXXXXXXX"  # SMTP授权码
    receivers = UserEmail   # 或= ['xxx@iou.ink'] 接收邮件的邮箱/发送给谁
    sender = 'XXXX'   # 英语懂?
    mail_msg = """
    <div style="margin: auto;text-align: center;">
	<h1>您的验证码为</h1>
	<code id="verify" style="background-color: #000000;color: red;font-size: 48px;font-family: arial rounded mt bold;letter-spacing: 10px;border-radius: 10px;">"""+verification_code+"""</code>
	<br> <br> <br> <br>
	<h2><img src="https://xyxywan.gitee.io/img/toux.jpg" style=" font-weight: normal; width: 100px; height: 100px; border-radius: 10px;">
	<a href="https://xn--15t.top/" style="text-decoration: none;font-size: 72px;color: #00aaff;font-family: arial narrow;">&nbsp;Yuxin Official</a>
	</h2>
	</div>
    """
    #邮件内包含的html内容

    message = MIMEText(mail_msg, 'html', 'utf-8')
    message['From'] = Header("Yuxin Officeal", 'utf-8') # 邮件显示的发件人
    message['To'] = Header(UserEmail, 'utf-8')  # 邮件显示的收件人
    subject = '来自iou.ink的验证邮件'  # 邮件标题
    message['Subject'] = Header(subject, 'utf-8')
    try:
        smtpObj = smtplib.SMTP_SSL(mail_host, 465)  # 启用SSL发信, 端口一般是465
        #smtpObj = smtplib.SMTP()
        #smtpObj.connect(mail_host, 25)  # 25 为 SMTP 端口号
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(sender, receivers, message.as_string())
        print("邮件发送成功")
        returnd = str(' Email Sended to :'+UserEmail)
        return returnd
    except smtplib.SMTPException:
        print("Error: 无法发送邮件")


def WriteJson():
    # 生成当前请求注册的用户信息
    verify = {
        'UserID':UserID,
        'UserEmail': UserEmail,
        'IP':UserIP,
        'verification_code': verification_code,
        'date': date
    }
    try:
        # 信息写入写入json供前端查询验证
        with open('verify.json', 'w') as f01:
            json.dump(verify, f01,indent=1)
            print(json.dumps(verify, indent=1))
            f01.close()
        # 信息写入写入历史记录
        output_dir = './'
        listdir = os.listdir(output_dir)
        if 'history.json' in listdir:
            fr1 = open(pjoin(output_dir, 'history.json'), 'a')
            model = json.dumps(verify, indent=1)
            fr1.write(model)
            fr1.close()
        print("WriteJson Complete！")
    except:
        print("WriteJson Error！")
    print("WriteJson ended！")


SendEmail()
